import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { Setofkey } from "../../../../entity/setofkey.model";
import { SetofkeyService } from "../../../../service/setofkey.service";
import { Observable } from "rxjs/Observable";
import { Command } from "../../../../shared/toolbar.service";
import { Blade } from "../../../../shared/blade/blade.model";
import { BladeData } from "../../../../shared/blade/blade-data";
import { DicKeyEditComponent } from "../../../../module/basic/dic/dic-key-edit/dic-key-edit.component";
import { DicValueListComponent } from "../../../../module/basic/dic/dic-value-list/dic-value-list.component";
import { Farm } from "../../../../entity/farm.model";
import { FarmEditComponent } from "../farm-edit/farm-edit.component";
import { FarmService } from "../../../../service/farm.service"
import { DialogResult } from "../../../../shared/dialog.service";
import { Phase } from "../../../../entity/phase.model";
import { PhaseListComponent } from "../../phase/phase-list/phase-list.component";
import { CircuitListComponent } from "../../circuit/circuit-list/circuit-list.component";
import { StationTagListComponent } from "../../station-tag/station-tag-list/station-tag-list.component";
import { CalculateExpressionListComponent } from '../../calculate-expression/calculate-expression-list/calculate-expression-list.component';
import { ApplicationService } from "../../../../service/application.service";
import { ValueDict } from "../../../../entity/setof-dict.model";

@Component({
    selector: 'app-farm-list',
    templateUrl: './farm-list.component.html',
    styleUrls: ['./farm-list.component.css']
})

export class FarmListComponent extends BladeContainerBase<Farm>{
    farms: Farm[] = [];
    original: Farm[] = [];
    valueDict: ValueDict;
    constructor(
        private farmService: FarmService,
        private application: ApplicationService,
    ) {
        super();
        this.valueDict = this.application.setValueDict["FarmCategory"];
        // this.bladeData.headIcon=  this.application.currentMenu.menuIcon;
    }
    ngOnInit(): void {
        this.commands = [
            new Command("add", "添加", "fa fa-plus", "asset:create", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
            new Command("edit", "编辑", "fa fa-edit", "asset:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
            new Command("delete", "删除", "fa fa-trash-o", "asset:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade)),
            new Command("phase", "工期", "fa fa-cubes", "setofkey:circuit", blade => this.exePhaseList(blade), blade => this.canExeEdit(blade)),
            new Command("circuit", "线路", "fa fa-barcode", "setofkey:circuit", blade => this.exeCircuitList(blade), blade => this.canExeEdit(blade)),
            new Command("station-tag", "关口表", "fa fa-dot-circle-o", "setofkey:station-tag", blade => this.exeStationTagList(blade), blade => this.canExeEdit(blade)),
           // new Command("station-tag", "电量公式", "fa fa-dot-circle-o", "setofkey:station-tag", blade => this.exeExpressionList(blade), blade => this.canExeEdit(blade)),
        ];
        super.ngOnInit();
    }
    /**
     * 初始化数据
     * 
     * 
     * @memberof FarmListComponent
     */
    initData(): any | Observable<any> | Promise<any> {
        this.farmService.getFarms()
            .then(res => {
                if (!res) { return false; };
                this.original = [...res];
                this.farms = [...this.original];
                this.farms.forEach(farm => {
                    if (this.valueDict[farm.farmCategory]) {
                        farm.farmCategoryName = this.valueDict[farm.farmCategory].valueDisplay;
                    }
                });
                this.currentEntity = this.farms[0];
                this.onSeletedChange(this.currentEntity);
            })
            .catch(error => this.bladeData.error = error)
            .then(res => this.bladeData.isLoading = false);
    }

    exeAdd(blend: Blade): void {
        let data: BladeData = new BladeData();
        data.id = "farmEdit";
        data.title = "新增风场";
        data.isClosingDisabled = false;
        let createKeyBlade = this.bladeService.createBlade(FarmEditComponent, data, true, null, this.currentEntity);
        this.bladeService.showBlade(createKeyBlade, this.currentBlade);
    }
    canExeAdd(blend: Blade): boolean {
        return true;
    }
    //编辑
    exeEdit(blend: Blade): void {
        if (this.currentEntity != undefined) {
            let data: BladeData = new BladeData();
            data.id = "farmEdit";
            data.title = this.currentEntity.farmName;
            let editKeyBlade = this.bladeService.createBlade(FarmEditComponent, data, false, this.currentEntity);
            this.currentBlade.bladeService.showBlade(editKeyBlade, this.currentBlade);
        }
    }
    canExeEdit(blend?: Blade): boolean {
        return this.currentEntity != null;
    }

    /**  
        exeDelete(blend: Blade): void {
            let selectedKeys = this.getSelected();
            if (selectedKeys.length > 0) {
                this.dialogService
                    .showConfirmationDialog("确认删除", "是否要删除选中项？")
                    .subscribe(dialogResult => {
                        if (dialogResult == DialogResult.Ok) {
                            this.currentBlade.bladeData.isLoading = true;
                            this.farmService.batchDelete(selectedKeys.map(o => o.farmId))
                                .then(res => {
                                    if (res) {
                                        this.refresh(undefined);
                                    }
                                })
                                .catch(error => this.bladeData.error = error)
                                .then(res => this.bladeData.isLoading = false);
                        }
                    })
            }
    
        }
    */

    exeDelete(blend: Blade): void {
        let selectedKeys = this.getSelected();
        if (selectedKeys.length > 0) {
            this.dialogService
                .showConfirmationDialog("确认删除", "是否要删除选中项？")
                .subscribe(dialogResult => {
                    if (dialogResult == DialogResult.Ok) {
                        this.currentBlade.bladeData.isLoading = true;
                        this.farmService.batchDelete(selectedKeys.map(o => o.farmId))
                            .then(res => {
                                if (res.code == '200') {
                                    super.refresh(undefined);
                                }
                                if (res.code == '8001') {
                                    this.dialogService
                                        .showConfirmationDialog("删除失败", res.message);
                                }
                            })
                            .catch(error => this.bladeData.error = error)
                            .then(res => this.bladeData.isLoading = false);
                    }
                })
        }

    }
    canDelete(blend?: Blade): boolean {
        return this.getSelected().length > 0;
    }

    //风场对应线路信息组件
    exeCircuitList(blend: Blade): void {
        if (this.currentEntity != undefined) {
            let data: BladeData = new BladeData();
            data.id = "showCircircuitList";
            data.title = this.currentEntity.farmName + "线路列表";
            data.isClosingDisabled = false;
            let showCircuitComponent = this.bladeService.createBlade(CircuitListComponent, data, false, null, this.currentEntity);
            this.bladeService.showBlade(showCircuitComponent, this.currentBlade);
        }
    }
    //风场对应工期组件   
    exePhaseList(blend: Blade): void {
        if (this.currentEntity != undefined) {
            let data: BladeData = new BladeData();
            data.id = "showPhaseList";
            data.title = this.currentEntity.farmName + "工期列表";
            data.isClosingDisabled = false;
            let showCircuitComponent = this.bladeService.createBlade(PhaseListComponent, data, false, null, this.currentEntity);
            this.bladeService.showBlade(showCircuitComponent, this.currentBlade);
        }
    }
    // 风场对应关口表
    exeStationTagList(blend: Blade): void {
        if (this.currentEntity != undefined) {
            let data: BladeData = new BladeData();
            data.id = "showStationTagList";
            data.title = this.currentEntity.farmName + "关口表列表";
            data.isClosingDisabled = false;
            let showStationTagComponent = this.bladeService.createBlade(StationTagListComponent, data, false, null, this.currentEntity);
            this.bladeService.showBlade(showStationTagComponent, this.currentBlade);
        }
    }

    // 风场对应电量表达式
    exeExpressionList(blend: Blade): void {
        if (this.currentEntity != undefined) {
            let data: BladeData = new BladeData();
            data.id = "showExpressionList";
            data.title = this.currentEntity.farmName + "电量表达式";
            data.isClosingDisabled = false;
            let showExpressionComponent = this.bladeService.createBlade(CalculateExpressionListComponent, data, false, null, this.currentEntity);
            this.bladeService.showBlade(showExpressionComponent, this.currentBlade);
        }
    }

    /**
     * 单选
     * 
     * @param {any} event 
     * @param {any} key 
     * 
     * @memberof FarmListComponent
     */
    onItemCheack(event: HTMLInputElement, key: Farm) {
        key.isChecked = event.checked;
    }
    /**
     * 全选/全不选
     * 
     * @param {any} event 
     * 
     * @memberof FarmListComponent
     */
    onAllCheack(event: HTMLInputElement) {
        if (this.farms.length > 0) {
            for (let i = 0; i < this.farms.length; i++) {
                this.farms[i].isChecked = event.checked;
            }
        }
    }
    onSeletedChange(farm: Farm) {
        if (this.currentBlade.childrenCanDeactivate()) {
            this.showPhaseListBlade(farm);
        }
    }


    /**
     * 展开列表弹出层
     * 
     * @param {Farm} farm 
     * 
     * @memberof FarmListComponent
     */

    // showFarmListBlade(selectedKey: Farm) {
    //     if (this.currentEntity != selectedKey
    //         || this.bladeService.findBlade("dicValueEdit") == undefined) {

    //         let data: BladeData = new BladeData();
    //         data.id = "farmList";
    //         data.title = selectedKey.farmName + "列表";
    //         // data.subtitle = this.currentEntity.keyDesc;
    //         data.isClosingDisabled = false;
    //         let FarmEditBlade = this.bladeService.createBlade(FarmEditComponent, data, false, selectedKey);
    //         this.bladeService.showBlade(FarmEditBlade, this.currentBlade).then(res => {
    //             if (res) {
    //                 this.currentEntity = selectedKey;
    //             }
    //         });
    //     }
    // }

    showPhaseListBlade(selectedFarm: Farm) {
        if (this.currentEntity != selectedFarm
            || this.bladeService.findBlade("showCircircuitList") == undefined) {

            let data: BladeData = new BladeData();
            data.id = "showCircircuitList";
            data.title = selectedFarm.farmName + "工期列表";
            // data.subtitle = this.currentEntity.keyDesc;
            data.isClosingDisabled = false;
            let PhaseListBlade = this.bladeService.createBlade(PhaseListComponent, data, false, null, selectedFarm);
            this.bladeService.showBlade(PhaseListBlade, this.currentBlade).then(res => {
                if (res) {
                    this.currentEntity = selectedFarm;
                }
            });
        }
    }

    /**
     * 获得选中项
     * 
     * @returns {Setofkey[]} 
     * 
     * @memberof FarmListComponent
     */
    getSelected(): Farm[] {
        if (this.farms.length > 0) {
            let filter = this.farms.filter(ref => ref.isChecked)
            return filter == null ? [] : filter;
        }
        return [];
    }
}




// WEBPACK FOOTER //
// ./src/app/module/basic/farm/farm-list/farm-list.component.ts